#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include<cstring>

void Usage(std::string proc)
{
  std::cout << proc << " port" << std::endl;
}
int main(int args, char *argv[])
{
  if (args != 2)
  {
    Usage(argv[0]);
    return 1;
  }
  // 创建套接字
  int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
  if (sock_fd < 0)
  {
    std::cerr << "socket is error" << errno << std::endl;
    return 2;
  }
  // bind
  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(atoi(argv[1]));
  server.sin_addr.s_addr = INADDR_ANY;
  socklen_t server_len = sizeof(server);
  if (bind(sock_fd, (sockaddr *)&server, server_len) < 0)
  {
    std::cerr << "bind is error" << errno << std::endl;
    return 3;
  }

  // 监听
  if (listen(sock_fd, 5) < 0)
  {
    std::cerr << "listen is error" << errno << std::endl;
    return 4;
  }
  

  // 接受
  for (;;)
  {
    struct sockaddr_in waiter;
    socklen_t waiter_len = sizeof(waiter);
    int server_fd = accept(sock_fd, (sockaddr *)&waiter_len, &waiter_len);
    if(server_fd < 0)
    {
      continue;
    }
    //使用server_fd这个网络文件的文件描述符进行通信
    //开始业务
    char arr[2048];
    memset(arr,0,sizeof(arr));
    ssize_t size = read(server_fd,arr,sizeof(arr));
    arr[size] = 0;//'\0'

    std::cout << arr << std::endl;
    std::string echo_hello = "hello";
    write(server_fd,(void*)echo_hello.c_str(),echo_hello.size());
  }

  return 0;
}
